import React, { useState, useEffect, useRef } from "react";
import { Tabs, Selector } from 'antd-mobile';
import { UpOutline, DownOutline } from 'antd-mobile-icons'
//
import './Categray.scss';
import BookCard from '../../components/BookCard/BookCard';
import useTouchBottom from "../../hooks/useTouchBottom/index";
export default function Categray() {
   // 一级
   const [cate, setCates] = useState([]);
   // 索引
   const [activeKey, setActiveKey] = useState(null);
   // 二级
   const [catetwo, setCatetwos] = useState([]);
   const [catUrl, setCatUrl] = useState(null);
   // 三级
   const [filters, setFilters] = useState([]);
   const [myRadio, setMyRadio] = useState({});
   // const [catUrl, setCatUrl] = useState(null);
   // 筛选
   const [sortest, setSortest] = useState(false)
   // 最终数据
   let [bookList, setBookList] = useState([]);
   // 拼接数据
   let bookRef = useRef([]);
   // 触底加载数据 
   const bookUrl = useRef("");


   // 获取 一级 二级 标题数据
   useEffect(() => {
      React.axios('mergedCategroy.json').then(res => {
         setCates(res)
         setActiveKey(0)
         setCatetwos(res[0].cates);
         // console.log(res, res[0].cates)
      }).catch(err => {
         console.log(err)
      });
   }, []);
   // const handleClick = (k) => {
   //    console.log('check', k)
   // }
   // activeKey 变化 赋值 重组
   useEffect(() => {
      // 异步  
      // console.log('000', filters);
      // setFilters(filters)
      setTimeout(() => {
         let tempObj = cate[activeKey].cates.map((o) => ({ ...o, label: o.name, value: o.url }))
         setCatetwos(tempObj);
      })
   }, [activeKey]);
   //   分类变化的时候 获取分类列表的第一项 改变当前分类
   useEffect(() => {
      if (catetwo.length) {
         setCatUrl(catetwo[0].value);
      }
   }, [catetwo]);

   //   监听当前分类变化 获取过滤器
   useEffect(() => {
      // 获取分类筛选条件
      catUrl &&
         React.axios
            .get(catUrl)
            .then(function (res) {
               // console.log(res.categories);
               setFilters(res.categories);
               // setFilters(filters)
            })
            .catch(function (error) {
               console.log(error);
            });
   }, [catUrl]);

   // 监听过滤器变化 设置选择默认值
   useEffect(() => {
      // console.log('filters', filters);
      if (filters.length) {
         let o = {};
         filters.forEach((f) => {
            o[f.type] = f.catArray[0].value;
         });
         setMyRadio(o);
         // console.log('filters=======>', myRadio);
      }
   }, [filters]);
   //  侦听  myRadio 
   useEffect(() => {
      console.log('myRadio', myRadio);
      catUrl &&
         React.axios
            .get("source/v2/searchBook.json", {
               params: {
                  catId: new URL("http://www.qq.com" + catUrl).searchParams.get("catId"),
                  ...myRadio,
               },
            })
            .then(function (res) {
               console.log(res);
               // setBookUrl(res.next)
               bookUrl.current = res.next
               setBookList(res.list);
               bookRef.current = res.list
               // bookList.current = res.list
               // currentVal(res.list)
            })
            .catch(function (error) {
               console.log(error);
            });
   }, [myRadio]);

   // 
   let handleLoadMore = () => {
      // console.log('触底了--------', bookUrl.current)
      if (bookUrl.current) {
         React.axios
            .get(bookUrl.current)
            .then(function (res) {
               // console.log("触底了", res.list,);
               // 下一页
               bookUrl.current = res.next
               // 最新数据 拼接数据
               bookRef.current = bookRef.current.concat(res.list);
               setBookList([...bookRef.current])
            })
      }
   };

   // 触底加载
   useTouchBottom(handleLoadMore);


   return cate && catetwo &&bookList&& <div className="categray">
      <Tabs
         style={{
            "--title-font-size": "16px",
         }}
         activeKey={activeKey}
         onChange={(key) => setActiveKey(key)}
      >
         {cate.map((item, index) => (
            <Tabs.Tab title={item.name} key={index} />
         ))
         }
      </Tabs>
      {/* <ul className="cate_list">
         {catetwo.map((item, index) => (
            <CategrayList key={index} txtstr={catetwo[0].name} list={item}></CategrayList>
         ))
         }
         // 这样子写，有问题，难搞，多次点击出问题
      </ul> */}
      <div className="cate_list">
         <div className="list_con">
            <Selector
               style={{
                  '--border-radius': '6px',
                  '--border': 'solid transparent 1px',
                  '--checked-border': 'solid transparent 1px',
                  '--padding': '4px 14px',
                  '--color': '#F5F5F5'
               }}
               showCheckMark={false}
               options={catetwo}
               value={[catUrl]}
               onChange={(v) => {
                  if (v.length) {
                     setCatUrl(v[0]);
                  }
               }}
            />
         </div>
      </div>
      {/* 最新  畅销 */}

      {/* 筛选 */}
      <div className="cate_filter">
         {filters.filter((o) => o.isTop).map((item, index) => (
            <div className="newest">
               <div className="news_txt">
                  {item.catArray.map((e, i) => (
                     <span className={`well ${myRadio.sort === e.value ? 'active' : ""}`}
                        data-val={e.value}
                        onClick={(event) => setMyRadio({ ...myRadio, ["sort"]: Number(event.target.dataset.val) })}
                     //  onClick={(o) => console.log(o.target.dataset.val)}
                     >{e.name}</span>
                  ))}
               </div>
               <div className="sort_txt" onClick={() => setSortest(!sortest)}>
                  筛选&nbsp;
                  {sortest === false ? <UpOutline /> : <DownOutline />}
               </div>
            </div>
         ))}
         {/*  */}
         <div>
            {sortest && filters.filter((o, index) => !o.isTop).map((item, index) => (
               <div className="fi_all" >
                  {item.catArray.map((ie, ii) => (
                     <span
                        className={`all_item ${myRadio[filters[index].type] === ie.value ? 'item_active' : ''}`}
                        data-val={ie.value}
                        onClick={(event) => setMyRadio({ ...myRadio, [filters[index].type]: Number(event.target.dataset.val) })}
                     >{ie.name}</span>
                  ))}
               </div>
            ))}
         </div>

      </div>
      {/* 数据list */}
      <ul className="card_list">
         {bookList.map((item, index) => (
            <BookCard key={index} book={item} width={30}></BookCard>
         ))}
      </ul>
   </div>
}